﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Common;
using EcSalseManage.App_Code;
using System.IO;
using System.Net;

namespace EcSalseManage.EcSalse
{
    public partial class Report_Change_Detail : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                 if (!CommonFunction.isInPrev("Report_Change_0001"))
                 {
                     Response.Redirect("../Error/Perm_Error.aspx");
                 }
                 if (!CommonFunction.isInPrev("Report_Change_0002"))
                 {
                     this.btnSave.Enabled = false;
                 }
                 if (!CommonFunction.isInPrev("Report_Change_0003"))
                 {
                     this.btnDelete.Enabled = false;
                 }


                 this.btnSave.Attributes.Add("onclick", "javascript:if(Page_ClientValidate()) return DataCheck();");

                DataAccess.Operate.DA_Report_Attach_Inherit Report_Attach_Inherit = new DataAccess.Operate.DA_Report_Attach_Inherit();
                DataSet ds = Report_Attach_Inherit.FindLibrary();
                Common.Common_Function.DropDownListBind(ddlFileType, ds.Tables[0], "Report_File_ID", "Report_File_Name", "", "--请选择附件类型--");
                this.btnUpLoad.Attributes.Add("onClick", "return checkUpload()");


                if (Request.QueryString["typeid"].ToString() == "5")
                    this.lblTitle.Text = "转单位";
                else if (Request.QueryString["typeid"].ToString() == "6")
                    this.lblTitle.Text = "买家变更";

                this.Report_Tab1.ExchangeTypeID = Request.QueryString["typeid"].ToString();
                if (Request.QueryString["id"] != null)
                {
                    ViewState["id"] = Request.QueryString["id"].ToString();
                    Update_Data_Bind(ViewState["id"].ToString());
                    this.dgList.Visible = true;
                    BindGrid();
                    btnUpLoad.Visible = true;
                    dgList.Visible = true;
                    this.btnUpLoad.Visible = true;
                    btnReset.Visible = false;
                    btnDelete.Visible = true;
                    this.Report_Tab1.Visible = true;
                    this.Report_Tab1.MainID = ViewState["id"].ToString();
                   
                }
                else if(Session["ProjectID"]!=null)
                {
                    DataAccess.Operate.DA_Project_Inherit Project_Inherit = new DataAccess.Operate.DA_Project_Inherit();
                    this.lblProjectName.Text = Project_Inherit.getProjectName(Session["ProjectID"].ToString());
                    ViewState["id"] = null;
                    this.btnAudit.Visible = false;
                }
            }

        }
        private void Update_Data_Bind(string id)
        {

            DataAccess.Operate.DA_Report_Change_Operate Report_Change_Operate = new DataAccess.Operate.DA_Report_Change_Operate();
            DataEntity.T_Report_Change Report_Change = new DataEntity.T_Report_Change();
            Report_Change = (DataEntity.T_Report_Change)Report_Change_Operate.SelectOne(id);

            txtReport_Change_Address.Text = Report_Change.Report_Change_Address.ToString();
            txtReport_Change_Building.Text = Report_Change.Report_Change_Building.ToString();
            txtReport_Change_Client.Text = Report_Change.Report_Change_Client.ToString();
            txtReport_Change_ReviseDate.Text = Report_Change.Report_Change_ReviseDate.ToString();
            txtReport_Change_ReportNO.Text = Report_Change.Report_Change_ReportNO.ToString();
            txtReport_Change_Reason.Text = Report_Change.Report_Change_Reason.ToString();
            txtReport_Change_ReviseAddress.Text = Report_Change.Report_Change_ReviseAddress.ToString();
            txtReport_Change_ReviseClient.Text = Report_Change.Report_Change_ReviseClient.ToString();
            txtReport_Change_Other.Text = Report_Change.Report_Change_Other.ToString();

            DataAccess.Operate.DA_Project_Inherit Project_Inherit = new DataAccess.Operate.DA_Project_Inherit();
            this.lblProjectName.Text = Project_Inherit.getProjectName(Report_Change.Report_Change_ProjectID.ToString());
            ViewState["ProjectID"] = Report_Change.Report_Change_ProjectID.ToString();

            if (Report_Change.Report_Plan_Audit >20)
            {
                this.btnSave.Enabled = false;
                this.btnDelete.Enabled = false;
            }
            if (Report_Change.Report_Plan_Audit == 20)
                this.btnAudit.Text = "营销[副]总监审核";
             if (Report_Change.Report_Plan_Audit == 22)
                 this.btnAudit.Text = "事总审核";
             if (Report_Change.Report_Plan_Audit == 23)
                 this.btnAudit.Text = "部门负责人审核";
             if (Report_Change.Report_Plan_Audit == 24)
             {
                 this.btnAudit.Text = "审核已完成";
                 this.btnAudit.Enabled = false;
             }

             if (!CommonFunction.isInPrev("Report_Change_0005") && this.btnAudit.Text == "营销[副]总监审核")
             {
                 this.btnAudit.Enabled = false;
             }
             if (!CommonFunction.isInPrev("Report_Change_0006") && this.btnAudit.Text == "事总审核")
             {
                 this.btnAudit.Enabled = false;
             }
             if (!CommonFunction.isInPrev("Report_Change_0007") && this.btnAudit.Text == "部门负责人审核")
             {
                 this.btnAudit.Enabled = false;
             }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            DataAccess.Operate.DA_Report_Change_Operate Report_Change_Operate = new DataAccess.Operate.DA_Report_Change_Operate();
            DataEntity.T_Report_Change Report_Change = new DataEntity.T_Report_Change();
            Report_Change.Report_Change_Address = txtReport_Change_Address.Text.Trim();
            Report_Change.Report_Change_Building = txtReport_Change_Building.Text.Trim();
            Report_Change.Report_Change_Client = txtReport_Change_Client.Text.Trim();
            Report_Change.Report_Change_ReviseDate = Convert.ToDateTime(txtReport_Change_ReviseDate.Text.ToString());
            Report_Change.Report_Change_ReportNO = txtReport_Change_ReportNO.Text.Trim();
            Report_Change.Report_Change_Reason = txtReport_Change_Reason.Text.Trim();
            Report_Change.Report_Change_ReviseAddress = txtReport_Change_ReviseAddress.Text.Trim();
            Report_Change.Report_Change_ReviseClient = txtReport_Change_ReviseClient.Text.Trim();
            Report_Change.Report_Change_Other = txtReport_Change_Other.Text.Trim();
            Report_Change.Report_Change_ExchangeTypeID =Convert.ToInt32(this.Report_Tab1.ExchangeTypeID);
            Report_Change.Report_Change_ExchangeDate = Convert.ToDateTime(DateTime.Now.ToString()); // 注意
            Report_Change.Report_Change_UpdateReason = ""; //注意
            Report_Change.Report_Change_Update = "";
            Report_Change.Report_Plan_Audit = 20;
            Guid gReport = System.Guid.NewGuid();
            //拼接变更情况字段
            //if (Report_Change.Report_Change_Address != "")
            //{
            //    Report_Change.Report_Change_Update = "1.原成交物业地址" + Report_Change.Report_Change_Address + "改为" + Report_Change.Report_Change_ReviseAddress;
            //}
            //if (Report_Change.Report_Change_ReviseClient != "")
            //{
            //    Report_Change.Report_Change_Update += Report_Change.Report_Change_Update == "" ? "1.原客户姓名" + Report_Change.Report_Change_Client + "改为" + Report_Change.Report_Change_ReviseClient + "" : "。2.原客户姓名" + Report_Change.Report_Change_Client + "改为" + Report_Change.Report_Change_ReviseClient + "";
            //}

            if (ViewState["id"]==null)
            {
                Report_Change.Report_Change_ID = gReport;
                Report_Change.Report_Change_ProjectID = new Guid(Session["ProjectID"].ToString());
                if (Report_Change_Operate.Insert(Report_Change))
                {

                    DataAccess.Multi.System_Multi.addLog(Session["EmployeeID"].ToString(), Session["EmployeeName"].ToString(), 1, gReport, 1);
                   
                    #region 上传附件部分
                    DataAccess.Operate.DA_Report_Attach_Operate Report_Attach_Operate = new DataAccess.Operate.DA_Report_Attach_Operate();
                    DataEntity.T_Report_Attach Report_Attach = new DataEntity.T_Report_Attach();
                    string sFileName = "";
                    string sFilePath = "";
                    string sFileType = "";

                    if (!Directory.Exists("\\\\gzs-ecc02\\ReportManager\\" + DateTime.Now.Year.ToString()))
                    {
                        Directory.CreateDirectory("\\\\gzs-ecc02\\ReportManager\\" + DateTime.Now.Year.ToString());
                    }
                    if (!Directory.Exists("\\\\gzs-ecc02\\ReportManager\\" + DateTime.Now.Year.ToString() + "\\" + gReport.ToString()))
                    {
                        Directory.CreateDirectory("\\\\gzs-ecc02\\ReportManager\\" + DateTime.Now.Year.ToString() + "\\" + gReport.ToString());
                    }

                    sFileType = CommonFunction.CheckFileType(this.txtFilePath.PostedFile.FileName);
                    if (sFileType != "")
                    {
                        sFileName = gReport.ToString() + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + sFileType;
                    }

                    sFilePath = "/ReportManager/" + DateTime.Now.Year + "/" + gReport.ToString() + "/" + sFileName;
                    try
                    {
                        Report_Attach.Project_Report_FileDesc = this.txtProjectDesc.Text.Trim();
                        Report_Attach.Project_Report_FileName = sFileName;
                        Report_Attach.Project_Report_FilePath = sFilePath;
                        Report_Attach.Project_Report_ExchangeTypeID = 11;
                        Report_Attach.Project_Report_FileID = Convert.ToInt32(this.ddlFileType.SelectedValue);
                        Report_Attach.Project_Report_MainID = gReport;
                        Report_Attach_Operate.Insert(Report_Attach);
                        this.txtFilePath.PostedFile.SaveAs("\\\\gzs-ecc02\\ReportManager\\" + DateTime.Now.Year.ToString() + "\\" + gReport.ToString() + "\\" + sFileName);
                        DataAccess.Multi.System_Multi.addLog(Session["EmployeeID"].ToString(), Session["EmployeeName"].ToString(), 5, gReport, 4);

                    }
                    catch (System.Exception ex)
                    {
                        throw new Exception(ex.Message.ToString());
                    }
                    finally
                    {

                    }

                    #endregion
        
                    this.Page.ClientScript.RegisterStartupScript(typeof(Page), "", "<script>alert('" + Common_Const.MSG_ALL_INSERT_SUCCESS + "');window.close();</script>");
                    //通知营销副总监审批
                    SendMessage("5", Session["ProjectID"].ToString());
                    ClearForm();
                }
                else
                {
                    this.Page.ClientScript.RegisterStartupScript(typeof(Page), "", "<script>alert('" + Common_Const.MSG_ALL_INSERT_FAILS+ "');</script>");
                }
            }
            else
            {
                Report_Change.Report_Change_ID = new Guid(ViewState["id"].ToString());
                if (Report_Change_Operate.Update(Report_Change))
                {
                    DataAccess.Multi.System_Multi.addLog(Session["EmployeeID"].ToString(), Session["EmployeeName"].ToString(), 1, new Guid(ViewState["id"].ToString()), 2);
                    Response.Write("<script>alert('" + Common_Const.MSG_ALL_UPDATE_SUCCESS + "');window.close();</script>");
                }
                else
                {
                    Response.Write("<script>alert('" + Common_Const.MSG_ALL_UPDATE_FAILS+ "');</script>");
                }
            }
        }


        private void ClearForm()
        {
            Control frm = FindControl("Form1");
            foreach (Control ctrl in frm.Controls)
            {
                if (ctrl is TextBox)
                {
                    ((TextBox)ctrl).Text = " ";
                }
            }
        } 

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            DataAccess.Operate.DA_Report_Change_Operate Report_Change_Operate = new DataAccess.Operate.DA_Report_Change_Operate();
            if (Report_Change_Operate.Delete(ViewState["id"].ToString()))
            {
                Response.Write("<script>alert('" + Common_Const.MSG_ALL_DELETE_SUCCESS+ "');window.close();</script>");
                DataAccess.Multi.System_Multi.addLog(Session["EmployeeID"].ToString(), Session["EmployeeName"].ToString(), 1, new Guid(ViewState["id"].ToString()), 3);

            }
            else
            {
                Response.Write("<script>alert('" + Common_Const.MSG_ALL_DELETE_FAILS+ "');</script>");
            }
        }

        protected void btnUpLoad_Click(object sender, EventArgs e)
        {
            DataAccess.Operate.DA_Report_Attach_Operate Report_Attach_Operate = new DataAccess.Operate.DA_Report_Attach_Operate();
            DataEntity.T_Report_Attach Report_Attach = new DataEntity.T_Report_Attach();
            string sFileName = "";
            string sFilePath = "";
            string sFileType = "";

            Guid gReportID = new Guid(ViewState["id"].ToString());
            if (!Directory.Exists("\\\\gzs-ecc02\\ReportManager\\" + DateTime.Now.Year.ToString()))
            {
                Directory.CreateDirectory("\\\\gzs-ecc02\\ReportManager\\" + DateTime.Now.Year.ToString());
            }
            if (!Directory.Exists("\\\\gzs-ecc02\\ReportManager\\" + DateTime.Now.Year.ToString() + "\\" + gReportID.ToString()))
            {
                Directory.CreateDirectory("\\\\gzs-ecc02\\ReportManager\\" + DateTime.Now.Year.ToString() + "\\" + gReportID.ToString());
            }

            sFileType = CommonFunction.CheckFileType(this.txtFilePath.PostedFile.FileName);
            if (sFileType != "")
            {
                sFileName = gReportID.ToString() + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + sFileType;
            }

            sFilePath = "/ReportManager/" + DateTime.Now.Year + "/" + gReportID.ToString() + "/" + sFileName;
            try
            {
                Report_Attach.Project_Report_FileDesc = this.txtProjectDesc.Text.Trim();
                Report_Attach.Project_Report_FileName = sFileName;
                Report_Attach.Project_Report_FilePath = sFilePath;
                Report_Attach.Project_Report_ExchangeTypeID = 11;
                Report_Attach.Project_Report_FileID = Convert.ToInt32(this.ddlFileType.SelectedValue);
                Report_Attach.Project_Report_MainID = new Guid(gReportID.ToString());
                Report_Attach_Operate.Insert(Report_Attach);
                this.txtFilePath.PostedFile.SaveAs("\\\\gzs-ecc02\\ReportManager\\" + DateTime.Now.Year.ToString() + "\\" + gReportID.ToString() + "\\" + sFileName);
                DataAccess.Multi.System_Multi.addLog(Session["EmployeeID"].ToString(), Session["EmployeeName"].ToString(), 5, new Guid(gReportID.ToString()), 4);
                BindGrid();
            }
            catch (System.Exception ex)
            {
                throw new Exception(ex.Message.ToString());
            }
            finally
            {
                this.ddlFileType.SelectedValue = "";
            }
        }

        #region BindGrid
        private void BindGrid()
        {
            DataSet ds = new DataSet();
            DataAccess.Operate.DA_Report_Attach_Inherit Report_Attach_Inherit = new DataAccess.Operate.DA_Report_Attach_Inherit();
            ds = Report_Attach_Inherit.GetAllByReportID(ViewState["id"].ToString());
            dgList.DataSource = ds;
            dgList.DataBind();
        }
        #endregion

        protected void dgList_ItemDataBound(object sender, DataGridItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                if (e.Item.ItemIndex > -1)
                {
                    ImageButton imgbtnDelete = (ImageButton)e.Item.FindControl("imgbtnDelete");
                    imgbtnDelete.Attributes.Add("onclick", "return window.confirm(\"是否确定删除？\")");
                }
            }
        }

        protected void dgList_ItemCommand(object source, DataGridCommandEventArgs e)
        {
            DataAccess.Operate.DA_Report_Attach_Operate Report_Attach_Operate = new DataAccess.Operate.DA_Report_Attach_Operate();
            if (e.CommandName.ToString() == "Delete")
            {
                try
                {
                    Report_Attach_Operate.Delete(new Guid(dgList.DataKeys[e.Item.ItemIndex].ToString()));
                    DataAccess.Multi.System_Multi.addLog(Session["EmployeeID"].ToString(), Session["EmployeeName"].ToString(), 5, new Guid(ViewState["id"].ToString()), 3);
                    this.BindGrid();
                }
                catch (System.Exception ex)
                {
                    throw new Exception(ex.Message.ToString());
                }
                finally
                {
                    Report_Attach_Operate = null;
                }
            }
        }

        #region WebClient上传附件
        /// <summary>
        /// WebClient上传文件至服务器
        /// </summary>
        /// <param name="fileNamePath">文件名，全路径格式</param>
        /// <param name="uriString">服务器文件夹路径</param>
        public void UpLoadFile(string fileNamePath, string uriString)
        {
            /**/
            /// 创建WebClient实例 
            WebClient myWebClient = new WebClient();
            myWebClient.Credentials = CredentialCache.DefaultCredentials;
            // 要上传的文件 
            FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);
            // FileStream fs = OpenFile(); 
            BinaryReader r = new BinaryReader(fs);
            byte[] postArray = r.ReadBytes((int)fs.Length);
            Stream postStream = myWebClient.OpenWrite(uriString, " PUT ");
            try
            {

                // 使用UploadFile方法可以用下面的格式
                // myWebClient.UploadFile(uriString,"PUT",fileNamePath); 


                if (postStream.CanWrite)
                {
                    postStream.Write(postArray, 0, postArray.Length);
                    postStream.Close();
                    fs.Dispose();
                }
                else
                {
                    postStream.Close();
                    fs.Dispose();

                }
            }
            catch (Exception err)
            {
                postStream.Close();
                fs.Dispose();
                // Utility.LogWriter log = new Utility.LogWriter(); 
                throw err;
            }
            finally
            {
                postStream.Close();
                fs.Dispose();
            }
        }
        #endregion

        protected void btnAudit_Click(object sender, EventArgs e)
        {
            if (this.btnAudit.Text == "营销[副]总监审核")
            {
                DataAccess.Operate.DA_Report_Change_Inherit Report_Change_Inherit = new DataAccess.Operate.DA_Report_Change_Inherit();
                if(Report_Change_Inherit.AuditByID(ViewState["id"].ToString(),"22"))
                {
                   
                    DataAccess.Multi.System_Multi.addLog(Session["EmployeeID"].ToString(), Session["EmployeeName"].ToString(), 6, new Guid(ViewState["id"].ToString()), 5);
                    Response.Write("<script>alert('审核成功');window.close();</script>");
                    //通知事总审批
                    SendMessage("8", ViewState["ProjectID"].ToString());
                }
            }
            else if (this.btnAudit.Text == "事总审核")
            {
                DataAccess.Operate.DA_Report_Change_Inherit Report_Change_Inherit = new DataAccess.Operate.DA_Report_Change_Inherit();
                if (Report_Change_Inherit.AuditByID(ViewState["id"].ToString(), "23"))
                {
                    
                    DataAccess.Multi.System_Multi.addLog(Session["EmployeeID"].ToString(), Session["EmployeeName"].ToString(), 6, new Guid(ViewState["id"].ToString()), 8);
                    Response.Write("<script>alert('审核成功');window.close();</script>");
                    //通知部门负责人审批
                    SendMessage("6", ViewState["ProjectID"].ToString());
                }
            }
            else if (this.btnAudit.Text == "部门负责人审核")
            {
                DataAccess.Operate.DA_Report_Change_Inherit Report_Change_Inherit = new DataAccess.Operate.DA_Report_Change_Inherit();
                if (Report_Change_Inherit.AuditByID(ViewState["id"].ToString(), "24"))
                {
                    DataAccess.Multi.System_Multi.addLog(Session["EmployeeID"].ToString(), Session["EmployeeName"].ToString(), 6, new Guid(ViewState["id"].ToString()), 6);
                    Response.Write("<script>alert('审核成功');window.close();</script>");
                }
            }
        }

        //public void SendMessage(string purview, string project)
        //{
        //    string sTitle = "";
        //    string sBody = "";
        //    if (purview == "Report_Change_0005")
        //        sTitle = " 转单位、买家变更-营销[副]总监审批";
        //    else if (purview == "Report_Change_0006")
        //        sTitle = " 转单位、买家变更-事总审批";
        //    else if (purview == "Report_Change_0007")
        //        sTitle = " 转单位、买家变更-部门负责人审批";

        //    DataAccess.Operate.DA_Report_Plan_Inherit Report_Plan_Inherit = new DataAccess.Operate.DA_Report_Plan_Inherit();
        //    DataTable dt = Report_Plan_Inherit.GetCodeAndName(purview, project);
        //    for (int i = 0; i < dt.Rows.Count; i++)
        //    {
        //        string name = dt.Rows[i]["EmployeeName"].ToString();
        //        string code = dt.Rows[i]["Code"].ToString();
        //        EcSalseManage.App_Code.CommonFunction.SendMessage(name, code, sTitle, sBody);
        //    }
        //}

        public void SendMessage(string operate, string project)
        {
            string projectNo = "";
            DataAccess.Operate.DA_Project_Inherit Project_Inherit = new DataAccess.Operate.DA_Project_Inherit();
            string[] array = Project_Inherit.getCodeAndName(out projectNo, operate, project);
            string sTitle = "请注意，项目编号:" + projectNo + "中的转单位需要您的审批。";
            string sBody = "请注意，项目编号:" + projectNo + " 中的转单位需要您的审批。<a href='http://wap.gzcentaline.com.cn'>点击此处</a>";
            // array[1] 姓名 ，array[0] 工号
            EcSalseManage.App_Code.CommonFunction.SendMessage(array[1], array[0], sTitle, sBody);
        }





    }
}
